package com.wb.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class TcpClientHandler extends ChannelHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(ChannelHandlerAdapter.class);

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private Bootstrap bootstrap;

    public TcpClientHandler(){};

    public TcpClientHandler(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
        logger.info(" channels size : {}" , channels.size());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        logger.info(" msg : {} , ip : {} , port : {} ,size : {}" , msg.toString() , inetSocketAddress.getHostName() , inetSocketAddress.getPort() , channels.size());
        ctx.writeAndFlush(inetSocketAddress.getHostName()+ "sent to service !");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (!ctx.channel().metadata().hasDisconnect()) {
            InetSocketAddress inetSocketAddress = (InetSocketAddress)ctx.channel().remoteAddress();
            logger.info("已经断开,请重新连接!");
            NettyClientTest.doConnect(bootstrap, inetSocketAddress.getHostName() , inetSocketAddress.getPort());
        }
        logger.error("" , cause);
    }
}